package controllers

import javax.inject.Inject

import org.joda.time.DateTime

import scala.concurrent.{Await, Future, duration}, duration.Duration

import play.api.Logger

import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc.{Action, Controller, Request}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.{Json, JsObject, JsString}

import reactivemongo.api.gridfs.{GridFS, ReadFile}

import play.modules.reactivemongo.{
MongoController, ReactiveMongoApi, ReactiveMongoComponents
}

import reactivemongo.play.json._
import reactivemongo.play.json.collection._

import models.User

class Application @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents {
  def collection = reactiveMongoApi.database.map(_.collection[JSONCollection]("users"))

  def index = Action.async { implicit request =>
    val found = collection.map(_.find(Json.obj()).cursor[User]())

    found.flatMap(_.collect[List]()).map { users =>
      Ok(users.mkString(","))
    }.recover {
      case e =>
        e.printStackTrace()
        BadRequest(e.getMessage())
    }
  }

  def init = Action {
    val users = List(
      Json.obj(
        "name" -> "User1",
        "passwd" -> "mypassword",
        "email" -> "user1@some.com",
        "isValid" -> true,
        "registerTime" -> new DateTime().getMillis,
        "updateTime" -> new DateTime().getMillis
      ),

      Json.obj(
        "name" -> "User2",
        "passwd" -> "mypassword",
        "email" -> "user2@some.com",
        "isValid" -> true,
        "registerTime" -> new DateTime().getMillis,
        "updateTime" -> new DateTime().getMillis
      ),

      Json.obj(
        "name" -> "User3",
        "passwd" -> "mypassword",
        "email" -> "user3@some.com",
        "isValid" -> true,
        "registerTime" -> new DateTime().getMillis,
        "updateTime" -> new DateTime().getMillis
      ),

      Json.obj(
        "name" -> "User4",
        "passwd" -> "mypassword",
        "email" -> "user4@some.com",
        "isValid" -> true,
        "registerTime" -> new DateTime().getMillis,
        "updateTime" -> new DateTime().getMillis
      )
    )
    collection.flatMap(_.bulkInsert(users.toStream,ordered=true))
    Redirect(routes.UserController.list)
  }


}
